package cn.dankal.flyaudio.current.post

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import cn.carbs.android.expandabletextview.library.ExpandableTextView
import cn.dankal.basiclib.base.activity.BigPhotoActivity
import cn.dankal.basiclib.base.activity.BigPhotoActivity.URLS
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.util.AppUtils
import cn.dankal.basiclib.util.DisplayHelper.dp2px
import cn.dankal.basiclib.util.TimeUtil
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.basiclib.widget.banner.DkBanner
import cn.dankal.basiclib.widget.banner.IViewHolder
import cn.dankal.basiclib.widget.banner.VH
import cn.dankal.basiclib.widget.titlebar.TitleWithAction
import cn.dankal.business.pojo.CurrentBean
import cn.dankal.business.pojo.ReasonBean
import cn.dankal.business.Constants
import cn.dankal.business.eventbus.MessageDriverHomeEvent
import cn.dankal.business.eventbus.MessageDriverMyEvent
import cn.dankal.business.pojo.CommentBean
import cn.dankal.business.pojo.NotificationBean
import cn.dankal.flyaudio.R
import cn.dankal.flyaudio.current.post.detail.PostDetailActivity
import cn.dankal.flyaudio.home.MyCurrentPrsenter
import cn.dankal.flyaudio.personal.notificaiton.NotifyContract
import cn.dankal.flyaudio.personal.notificaiton.NotifyPresenter
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.listener.LockClickListener
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.shuyu.gsyvideoplayer.utils.Debuger
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import kotlinx.android.synthetic.main.activity_current_detail.*
import kotlinx.android.synthetic.main.layout_bottom_input_commend.*
import org.greenrobot.eventbus.EventBus
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager


/**
 * 包括视频和图片
 */
@Route(path = MainProtocol.CURRENT_DETAIL)
class CurrentDetailActivity : PostDetailActivity(), NotifyContract.View {
    lateinit var tv_action: TextView

    override fun delete(message: String?) {
        ToastUtils.showShort(message)
        EventBus.getDefault().postSticky(MessageDriverHomeEvent())
        EventBus.getDefault().postSticky(MessageDriverMyEvent())
        ToastUtils.showShort(message)
        finish()
    }

    override fun onRead() {

    }

    override fun render(t: MutableList<NotificationBean>?) {

    }

    override fun onUpdateRemind() {

    }

    @Autowired(name = Constants.UUID)
    @JvmField
    var uuid: String? = null

    @Autowired(name = "uuid_tow")
    @JvmField
    var uuidTow: String? = null

    @Autowired(name = "isShowDelete")
    @JvmField
    var isShowDelete: Boolean = false


    lateinit var currentBean: CurrentBean

    lateinit var dkBanner: DkBanner<String>
    var orientationUtils: OrientationUtils? = null
    private var isPause: Boolean = false
    private var isPlay: Boolean = true
    lateinit var url: String
    lateinit var notifyPresenter: NotifyPresenter
    lateinit var commonDialog: CommonDialog


    override fun getLayoutId(): Int {
        return R.layout.activity_current_detail
    }

    override fun initComponents() {
        super.initComponents()
        ARouter.getInstance().inject(this)
        var titleWithAction = TitleWithAction("此刻详情")
        addTitleBar(titleWithAction)

        tv_action = findViewById(R.id.tv_action)
        tv_action.setCompoundDrawables(null, null, null, null)
        if (isShowDelete) {
            tv_action.text = "删除"
            tv_action.setOnClickListener {

                val builder = CommonDialog.Builder(this)
                builder.setTitle("是否确认删除该信息？")

                builder.setNegativeButton("取消",
                        resources.getColor(R.color.color14)) {
                    commonDialog.dismiss()
                }

                builder.setPositiveButton("删除",
                        resources.getColor(R.color.colorPrimary)) {

                    var uuids = arrayOfNulls<String?>(1)
                    uuids[0] = uuid
                    notifyPresenter?.let {
                        it.deleteDetail(uuid)
                    }
                    commonDialog.dismiss()
                }
                commonDialog = builder.create()
                commonDialog.show()
            }
        } else {
            tv_action.setText("")
        }



        mPresenter.current_detail(uuid)
        initData(uuid)
        notifyPresenter = NotifyPresenter(2)
        notifyPresenter.attachView(this)
        notifyPresenter.update_remind_one(uuidTow, false)


    }


    override fun onCurrentDetailResult(bean: CurrentBean) {
        super.onCurrentDetailResult(bean)
        currentBean = bean
        super.initComponents()

        if (currentBean.type == null) {
            ToastUtils.showShort("没有此刻类型")
            ll_current_detail.visibility = View.GONE
            return
        }

        //图片
        if (currentBean.type == "1") {
            detailPlayer.visibility = View.GONE
            banner.visibility = View.VISIBLE
            dkBanner = banner as DkBanner<String>
            dkBanner.setIndicatorPoint(R.drawable.oval_indicator, R.drawable.oval_indicator_unselect,
                    dp2px(AppUtils.getApp(), 10), dp2px(AppUtils.getApp(), 10))

            dkBanner.setOnItemClickListener { view, banner, postion, _ ->
                var intent = Intent(this@CurrentDetailActivity, BigPhotoActivity::class.java)
                intent.putStringArrayListExtra(URLS, currentBean.list)
                intent.putExtra(BigPhotoActivity.PicIndex, postion)
                startActivity(intent)
            }
            dkBanner.setVpAdapter(currentBean.list, object : IViewHolder<String> {
                override fun create(): VH<String> {
                    return BannerItemView()
                }
            })

        }
        //视频

        else if (currentBean.type == "2") {
            detailPlayer.visibility = View.VISIBLE
            url = currentBean.list[0]
            initVideo()
        }



        currentBean.apply {
            PicUtils.loadAvatar(avatar, iv_user)
            tv_name.text = name
            tv_time.text = TimeUtil.friendly_time(TimeUtil.date2TimeStampLong(createTime, TimeUtil.DATEFORMATER, true))
            var tvContent: ExpandableTextView = findViewById(R.id.tv_content)
            tvContent.text = content
            tvContent.visibility = View.INVISIBLE
            var handler = android.os.Handler()
            handler.postDelayed(Runnable {
                tvContent.performClick()
                tvContent.performClick()
                tvContent.visibility = View.VISIBLE
            }, 800)
            mPresenter.setUuid(postId)
        }
    }


    private fun initVideo() {
        //外部辅助的旋转，帮助全屏
        orientationUtils = OrientationUtils(this, detailPlayer)
        //初始化不打开外部的旋转
        //orientationUtils?.setEnable(false)


        detailPlayer.setUp(PicUtils.QINIU_DOMAIN + url, true, "视频")

        //增加封面
        val imageView = ImageView(this)
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)
        PicUtils.loadNormal(url + "?vframe/jpg/offset/0", imageView)
        detailPlayer?.thumbImageView = imageView

        //增加title
        detailPlayer?.titleTextView?.visibility = View.VISIBLE
        //设置返回键
        detailPlayer?.backButton?.visibility = View.VISIBLE

        //是否可以滑动调整
        detailPlayer?.setIsTouchWiget(true)
        //设置返回按键功能
        detailPlayer?.backButton?.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View) {
                onBackPressed()
            }
        })
        detailPlayer?.startPlayLogic()

        detailPlayer.fullscreenButton.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                //直接横屏
                orientationUtils?.resolveByClick()

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                //detailPlayer.startWindowFullscreen(this@CurrentDetailActivity, true, true)
            }
        })


        detailPlayer.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                isPlay = true
            }

            override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                super.onQuitFullscreen(url, *objects)
                orientationUtils?.backToProtVideo()
            }
        })

        detailPlayer.setLockClickListener(object : LockClickListener {
            override fun onClick(view: View?, lock: Boolean) {
                orientationUtils?.setEnable(!lock)
            }
        })
    }


    override fun onBackPressed() {
        orientationUtils?.backToProtVideo()
        if (GSYVideoManager.backFromWindowFull(this)) {
            orientationUtils?.resolveByClick()
            return
        }
        //先返回正常状态
        /*   if (orientationUtils!!.screenType == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
               detailPlayer.fullscreenButton?.performClick()
               return
           }*/
        //释放所有
        detailPlayer.setVideoAllCallBack(null)

        super.onBackPressed()
    }


    override fun onPause() {
        detailPlayer.getCurrentPlayer().onVideoPause()
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        detailPlayer.getCurrentPlayer().onVideoResume(false)
        super.onResume()
        isPause = false
    }


    override fun onDestroy() {
        super.onDestroy()
        if (isPlay) {
            detailPlayer.getCurrentPlayer().release()
        }
        orientationUtils?.releaseListener()
    }


    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true)
        }
    }


    override fun onInnerCommentClick(name: String?, comment_id: String?, userId: String?, commentPosition: Int) {
        super.onInnerCommentClick(name, comment_id, userId, commentPosition)
        et_content.hint = "@$name"
        et_content.isFocusableInTouchMode = true
        et_content.requestFocus()
    }

    override fun onCommentResult(reasonBean: ReasonBean?, comment: CommentBean) {
        super.onCommentResult(reasonBean, comment)
        et_content.hint = "写下您的评论"
        et_content.setText("")
    }
}
